<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/19/019
 * Time: 16:31
 */

namespace Gate\Controller;

use Think\Controller;
use GatewayWorker\Lib\Gateway;
use Workerman\MySQL\Connection;
class EventsController extends Controller
{
    public static $group = 'group'; //规定聊天室名字
    public static $db;              //数据库链接
    //进程启动后与数据库建立异步长链接链接 因为此处
    public static function onWorkerStart($businessWorker)
    {
        //建立了mysql异步长连接
        self::$db =  new Connection(C('DB_HOST'), C('DB_PORT'), C('DB_USER'), C('DB_PWD'), C('DB_NAME'));
    }

    public static function onMessage($client_id, $data) {
        $message = json_decode($data, true);
        $type = $message['type'];

        switch ($type) {
            case 'init':
                self::processInit($client_id, $message);
                break;
            case 'chatMessage':
                self::processChatMessage($client_id, $message);
        }
    }

    //用户第一次登陆之后绑定用户信息
    private static function processInit($client_id, $message) {
        $uid = $message['uid'];
        // 设置session
        $_SESSION = array(
            'username' => $message['username'],
            'avatar'   => $message['avatar'],
            'uid'       => $uid,
        );
        //绑定id
        Gateway::bindUid($client_id, $uid);
        //加入聊天室 只有一个聊天室起名字叫 group
        Gateway::joinGroup($client_id, self::$group);
    }

    private static function processChatMessage($client_id, $message){
        //'1为文本 2为表情 3为文件',
       // $content_type = $message['data']['mine']['content_type'];
        $uid = $_SESSION['uid'];
        $type = $message['data']['to']['type'];
        $to_id = $message['data']['to']['id'];

        $chat_message = [
            'type' => 'chatMessage',
            'data' => [
                'username' => $_SESSION['username'],
                'avatar'   => $_SESSION['avatar'],
                'id'       => 'group',
                'type'     => 'group',
                'content'  => htmlspecialchars($message['data']['mine']['content']),
                'timestamp'=> time()*1000,
                'cid:'     => $uid
            ]
        ];

        //本信息只发给聊天室
        //聊天记录数组
        $param = [
            'fromid' => $uid,
            'content' => htmlspecialchars($message['data']['mine']['content']),
            'timeline' => time(),
        ];

        //把聊天记录写入数据库
        self::$db->insert('chatlog')->cols($param)->query();
        Gateway::sendToGroup('group', json_encode($chat_message), $client_id);
    }
    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id) {

    }
}